package com.memoryangelapplication;

/*
 * 
 * Back ground service classs to upload current event and get 
 * new and updated events from the server
 * 
 * */
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioManager;
import android.os.AsyncTask;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import com.memoryangelapplication.constant.MemoryAngelConstant;
import com.memoryangelapplication.services.DeviceInformation;
import com.memoryangelapplication.services.EventAlarm;
import com.memoryangelapplication.services.GMailSender;

public class BackgroundService extends Service {
	private static final String DATABASE_NAME = "memoryangel.db";
	private static final String TAG = null;
	// Master Tables
	private String MEM_USER = "table_user";
	private String MEM_EVENT = "table_events";
	private String MEM_DEVICE = "table_device";
	ArrayList<String> eventslist = new ArrayList<String>();
	InputStream is = null;
	StringBuilder sb = null;
	int timeoutConnection = 5000;
	HttpParams httpParameters = new BasicHttpParams();
	String result;
	private SQLiteDatabase mydb;
	String CareerPhone;
	String IMEINumber;
	int BateryLevel;
	int SIMState, Network = 0, currentVolume;
	String longitude = "0", latitude = "0";
	String deviceOpID;
	String sendingDeviceInfo = MemoryAngelConstant.MA_REGISTER;
	ArrayList<HashMap<String, String>> arraylist;
	JSONObject jsonobject;
	JSONArray jsonarray;
	double[] loc = new double[2];
	String event_user_id;
	String PhoneNo1;
	String CareerEmail = "";
	String CareerName, CareeerOPUser;
	String sumDateTime;
	long pasteventsLastTimeStamp = 0;
	String eventsalarmtimeschedule;
	String DateSend, Time, Tzone;
	long TimeStampValue;
	String deviceType, BateryLevelStr, currentVolumeStr;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO: Return the communication channel to the service.
		throw new UnsupportedOperationException("Not yet implemented");
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		/*
		 * Bundle bundle = new Bundle(); EventAlarm alarm1 = new
		 * EventAlarm(this, bundle, 60);
		 */
		long unixTime = System.currentTimeMillis() / 1000L;
		// Toast.makeText(getApplicationContext(), "Service Created", 1).show();
		super.onCreate();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		// Toast.makeText(getApplicationContext(), "Service Destroy", 1).show();
		super.onDestroy();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		//Log.e("MEM LOG", "Services Call***");
		long unixTime = System.currentTimeMillis() / 1000L;
		displayHeader();
		// Get Location Details
		GetLocationNetGPS gl = new GetLocationNetGPS(BackgroundService.this);
		loc = gl.GetLoc();
		latitude = loc[0] + "";
		longitude = loc[1] + "";

		// Get Device Type
		TelephonyManager phonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		DeviceInformation di = new DeviceInformation(BackgroundService.this);
		deviceType = di.getDeviceID(phonyManager);

		getDeviceInfo();
		getCurrentVolume();
		checkPreviousEvents();
		BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
			public void onReceive(Context context, Intent intent) {
				context.unregisterReceiver(this);
				int currentLevel = intent.getIntExtra(
						BatteryManager.EXTRA_LEVEL, -1);
				int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
				int level = -1;
				if (currentLevel >= 0 && scale > 0) {
					BateryLevel = (currentLevel * 100) / scale;
				}

			}
		};
		IntentFilter batteryLevelFilter = new IntentFilter(
				Intent.ACTION_BATTERY_CHANGED);
		registerReceiver(batteryLevelReceiver, batteryLevelFilter);

		saveDeviceInfo();
		// Time Zone Of the Current Phone
		Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"),
				Locale.getDefault());
		Date currentLocalTime = calendar.getTime();
		DateFormat date = new SimpleDateFormat("Z");
		Tzone = date.format(currentLocalTime);
		Tzone = " " + Tzone;
		getEvents();
		
		return super.onStartCommand(intent, flags, startId);
	}

	private void checkPreviousEvents() {
		// TODO Auto-generated method stub
		String nowunixtime = getAddDateTimeStringStamp().toString();

		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		Cursor checkPreviousAlerts = null;

		try {
			
			String query = "SELECT * FROM table_events Where event_active = '0' AND event_alam_time < '" + nowunixtime + "' AND event_ack_count = '0' ORDER BY event_log_id LIMIT 1";
			checkPreviousAlerts = mydb.rawQuery(query, null);
			/*checkPreviousAlerts = mydb.query(MEM_EVENT, null,
					"event_active = '0' AND event_alam_time < '" + nowunixtime
							+ "' AND event_ack_count = '0'", null, null, null, null);*/

		} catch (Exception e) {
		}
		if (checkPreviousAlerts != null) {
			if (checkPreviousAlerts.getCount() > 0) {
				while (checkPreviousAlerts.moveToNext()) {
					 // Log.e("MEM LOG :", "Trigger Previous Event From Service******");
					 Bundle bundle = new Bundle(); 
					 EventAlarm alarm1 = new EventAlarm(this, bundle, 1);
				}
			}
		}

	}

	private void saveDeviceInfo() {
		// TODO Auto-generated method stub
		// Log.e("MEM LOG", "Save Offline Device Info***");
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		Cursor allrawdevice = null;
		try {
			String query = "SELECT * FROM table_device";
			allrawdevice = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}
		if (allrawdevice != null) {
			if (allrawdevice.getCount() > 0) {
				while (allrawdevice.moveToNext()) {
					String devic_id = allrawdevice.getString(0);
					ContentValues updateDevice = new ContentValues();
					updateDevice.put("device_emi", deviceType);
					updateDevice.put("device_lon", longitude);
					updateDevice.put("device_lat", latitude);
					updateDevice.put("device_valume", currentVolume);
					updateDevice.put("device_battery", BateryLevel);
					updateDevice.put("device_update_time",
							getAddDateTimeString().toString());
				}
			} else {
				// Insert New Record
				ContentValues newregdevice = new ContentValues();
				newregdevice.put("device_emi", deviceType);
				newregdevice.put("device_lon", longitude);
				newregdevice.put("device_lat", latitude);
				newregdevice.put("device_valume", currentVolume);
				newregdevice.put("device_battery", BateryLevel);
				newregdevice.put("device_update_time", getAddDateTimeString()
						.toString());
				mydb.insert(MEM_DEVICE, null, newregdevice);
			}
		}
	}

	private void getEvents() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		Cursor allrowitemsdes = null;

		try {
			String query = "SELECT event_log_id,event_user_id,event_status,event_date,event_update_time,event_user_phoneno FROM table_events";
			allrowitemsdes = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}

		if (allrowitemsdes != null) {
			if (allrowitemsdes.getCount() > 0) {
				while (allrowitemsdes.moveToNext()) {
					String event_log_id = allrowitemsdes.getString(0);
					event_user_id = allrowitemsdes.getString(1);
					String event_status = allrowitemsdes.getString(2);
					String event_update_time = allrowitemsdes.getString(4);
					PhoneNo1 = allrowitemsdes.getString(5);
					try {
						JSONObject valuesJsonEvents = new JSONObject();
						valuesJsonEvents.put("event_op_id", event_user_id);
						valuesJsonEvents.put("event_id", event_log_id);
						valuesJsonEvents.put("event_status", event_status);
						valuesJsonEvents.put("event_ack_time",
								event_update_time);
						eventslist.add(valuesJsonEvents.toString());
					} catch (Exception e) {

					}
				}
			} else {
				try {
					JSONObject valuesJsonEvents = new JSONObject();
					valuesJsonEvents.put("event_op_id", deviceOpID);
					valuesJsonEvents.put("event_id", "0");
					valuesJsonEvents.put("event_status", "0");
					valuesJsonEvents.put("event_ack_time",
							getAddDateTimeString().toString());
					eventslist.add(valuesJsonEvents.toString());
				} catch (Exception e) {

				}
			}
		} else {
			try {
				JSONObject valuesJsonEvents = new JSONObject();
				valuesJsonEvents.put("event_op_id", deviceOpID);
				valuesJsonEvents.put("event_id", "0");
				valuesJsonEvents.put("event_status", "0");
				valuesJsonEvents.put("event_ack_time", getAddDateTimeString()
						.toString());
				eventslist.add(valuesJsonEvents.toString());
			} catch (Exception e) {

			}
		}
		allrowitemsdes.close();
		mydb.close();
		new fetchingEvents().execute();
	}

	private void displayHeader() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		Cursor cur_opuser = null;

		try {
			cur_opuser = mydb.query(MEM_USER, null, null, null, null, null,
					null);
		} catch (Exception e1) {
		}
		if (cur_opuser != null) {
			if (cur_opuser.getCount() > 0) {
				while (cur_opuser.moveToNext()) {
					deviceOpID = cur_opuser.getString(5);
					CareerEmail = cur_opuser.getString(2);
					CareerName = cur_opuser.getString(3);
					CareerPhone = cur_opuser.getString(4);
					CareeerOPUser = cur_opuser.getString(6);
					// Log.e("MEM LOG :", "CareerPhone****:"+CareerPhone);
				}
			}
		}
		cur_opuser.close();
		mydb.close();
	}

	// DownloadJSON AsyncTask
	private class fetchingEvents extends AsyncTask<Void, Void, Void> {

		private final String TAG = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
		}

		@Override
		protected Void doInBackground(Void... params) {
			// Get Events Results
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				// RegisterEventsUrl
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(
						"http://memoryangel.com/wakandroiddemo/wakandroid/UpdateandGetevent.php");
				JSONObject json = new JSONObject();
				json.put("reqEvents", eventslist);
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				String jsonStr = json.toString();
				String formatso1 = jsonStr.toString().replace("\\", "");
				String formatso2 = formatso1.toString().replace("}]\"}", "}]}");
				String formatso3 = formatso2.toString().replace("\"[{", "[{");
				// Log.v(TAG, "Request  EVENTS:" + formatso3);
				httppost.setHeader("json", formatso3);
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();

				if (is != null) {
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					// Log.v(TAG, "Responce XXX EVENTS:" + result);
					JSONObject jsonResponse = new JSONObject(result);
					JSONArray jsonArray = jsonResponse
							.getJSONArray("eventlist");
					for (int i = 0; i < jsonArray.length(); i++) {
						JSONObject jObject = (JSONObject) jsonArray.get(i);

						String CureventTimeID = jObject.getString("eventid");
						// Log.e("ERROR :", "CurrentStatus***CHK 1***:"+CureventTimeID);
						String dateString = jObject.getString("eventdate");
						
						DateSend = dateString;
						String dateTime = jObject.getString("eventtime");
						String[] CheckAMPM = dateTime.split(" ");
						String CheckHourMin = CheckAMPM[0];
						String CheckAMPMSTR = CheckAMPM[1];

						String[] CheckHourMinArr = CheckHourMin.split(":");
						String CheckHour = CheckHourMinArr[0];
						String CheckMin = CheckHourMinArr[1];

						if (CheckAMPMSTR.equals("PM")) {
							int CheckHourVal = Integer.parseInt(CheckHour);
							if (CheckHourVal != 12) {
								int CheckH = CheckHourVal + 12;
								CheckHour = Integer.toString(CheckH);
							} else {
								int CheckH = 12;
								CheckHour = Integer.toString(CheckH);
							}
						} else if (CheckAMPMSTR.equals("AM")
								&& CheckHour.equals("12")) {
							CheckHour = "00";
						}

						dateTime = CheckHour + "" + CheckMin + ""
								+ CheckAMPMSTR;
						Time = CheckHour + ":" + CheckMin;
						String CurrentTimeStamp = jObject
								.getString("eventtimestamp");
						String CurrentStatus = jObject.getString("status");
						//Log.e("ERROR :", "CurrentStatus***CHK 1***:"+CurrentStatus);
						dateString = dateString.replaceAll("-", "");
						dateTime = dateTime.replaceAll(":", "");

						String formatTimeStamp = dateString.trim() + ""
								+ CheckHour + "" + CheckMin;
						String formatTime = dateString.trim() + dateTime.trim();

						long formatTimeStampVal = Long
								.parseLong(formatTimeStamp);
						long formatTimeStampCurrent = Long
								.parseLong(getAddDateTimeStringPreCheck()
										.toString());
						getNativeTimeStamp(DateSend, Time, Tzone);

						/*
						 * if (formatTimeStampVal < formatTimeStampCurrent) { if
						 * (pasteventsLastTimeStamp == 0) {
						 * pasteventsLastTimeStamp = formatTimeStampCurrent;
						 * formatTimeStampVal = pasteventsLastTimeStamp + 1; }
						 * else { formatTimeStampVal = pasteventsLastTimeStamp +
						 * 1; }
						 * 
						 * }
						 */

						String TimeStampValueStr = String
								.valueOf(TimeStampValue);
						eventsalarmtimeschedule = String
								.valueOf(formatTimeStampVal);

						mydb = openOrCreateDatabase(DATABASE_NAME,
								Context.MODE_PRIVATE, null);

						try {
							Cursor checkPreEvents = null;
							CureventTimeID = CureventTimeID.trim();
							try {
								String query = "SELECT event_log_id,event_alam_time,event_status FROM table_events Where event_log_id = '"
										+ CureventTimeID + "'";
								checkPreEvents = mydb.rawQuery(query, null);
							} catch (Exception e) {
							}
							if (checkPreEvents != null) {
								if (checkPreEvents.getCount() > 0) {
									while (checkPreEvents.moveToNext()) {
										String updateID = checkPreEvents
												.getString(0);
										String updateTimeStamp = checkPreEvents
												.getString(1);
										String event_status = checkPreEvents
												.getString(2);
										
										Log.e("ERROR :", "Current STATUS:" + event_status + "SERVER :"+CurrentStatus);
										if (CurrentStatus.equals("6") || CurrentStatus.equals("0") || CurrentStatus.equals("1")) {
											int Status = 1;
											if(event_status.equals("3")){
												Log.e("ERROR :", "Already Acknoledge");
											}
											else{
											ContentValues updateEvets = new ContentValues();
											updateEvets
													.put("event_log_id",
															jObject.getString("eventid"));
											updateEvets.put("event_user_id",
													jObject.getString("opid"));
											updateEvets.put("event_title",
													jObject.getString("title"));
											updateEvets
													.put("event_description",
															jObject.getString("description"));
											updateEvets.put("event_status",
													Status);
											updateEvets
													.put("event_date",
															jObject.getString("eventdate"));
											updateEvets
													.put("event_time",
															jObject.getString("eventtime"));

											updateEvets.put("event_alam_time",
													eventsalarmtimeschedule);

											updateEvets
													.put("event_active", "0");
											updateEvets.put(
													"event_user_phoneno",
													CareerPhone);
											updateEvets.put("event_url",
													jObject.getString("url"));
											updateEvets
													.put("event_package",
															jObject.getString("package"));
											updateEvets.put("event_time_stamp",
													formatTime);
											updateEvets.put(
													"event_update_time",
													getAddDateTimeString()
															.toString());
											updateEvets.put("event_ack_count",
													"0");
											updateEvets
													.put("eventReminderTime",
															jObject.getString("eventremindertime"));
											updateEvets
													.put("eventReminderNumber",
															jObject.getString("eventremindernumber"));
											updateEvets
													.put("eventWaitTime",
															jObject.getString("eventwaittime"));
											updateEvets
													.put("eventNotifyType",
															jObject.getString("eventmissednotification"));
											updateEvets.put("eventTimeStamp",
													TimeStampValueStr);
											/*
											 * Log.e("ERROR :", "Update Event :"
											 * + jObject .getString("eventid"));
											 */
											mydb.update(MEM_EVENT, updateEvets,
													"event_log_id ='"
															+ updateID + "'",
													null);
											}
										}

										else if (CurrentStatus.equals("7")) {
											if(event_status.equals("3")){
												Log.e("ERROR :", "Already Acknoledge");
											}else{
											Log.e("ERROR :", "Event Delete******:"+event_status + "SERVER:" +CurrentStatus);
											ContentValues updateEvets = new ContentValues();
											updateEvets.put("event_status", "7");
											updateEvets.put("event_active", "1");
											mydb.update(MEM_EVENT, updateEvets,
													"event_log_id ='" + updateID
															+ "'", null);
											}

										} else {
											Log.e("ERROR :", "Event Not Changed");
										}

									}
								} else {
									// Log.v(TAG, "NEW RECORD SERVICE:" + CureventTimeID);
									int Status = 1;
								
									ContentValues newregevent = new ContentValues();
									newregevent.put("event_log_id",
											jObject.getString("eventid"));
									newregevent.put("event_user_id",
											jObject.getString("opid"));
									newregevent.put("event_title",
											jObject.getString("title"));
									newregevent.put("event_description",
											jObject.getString("description"));
									newregevent.put("event_status", Status);
									newregevent.put("event_date",
											jObject.getString("eventdate"));
									newregevent.put("event_time",
											jObject.getString("eventtime"));
									newregevent.put("event_alam_time",
											eventsalarmtimeschedule);
									newregevent.put("event_active", "0");
									newregevent.put("event_user_phoneno",
											CareerPhone);
									newregevent.put("event_url",
											jObject.getString("url"));
									newregevent.put("event_package",
											jObject.getString("package"));
									newregevent.put("event_time_stamp",
											formatTime);
									newregevent.put("event_update_time",
											getAddDateTimeString().toString());
									newregevent.put("event_ack_count", "0");
									newregevent
											.put("eventReminderTime",
													jObject.getString("eventremindertime"));
									newregevent
											.put("eventReminderNumber",
													jObject.getString("eventremindernumber"));
									newregevent.put("eventWaitTime",
											jObject.getString("eventwaittime"));
									newregevent
											.put("eventNotifyType",
													jObject.getString("eventmissednotification"));
									newregevent.put("eventTimeStamp",
											TimeStampValueStr);

									mydb.insert(MEM_EVENT, null, newregevent);
								}
							}

						} catch (Exception e) {
							Log.e("ERROR :", "Register Fail:" + e);
						}
						mydb.close();
					}

				}
			} catch (Exception e) {

			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			// Locate the listview in listview_main.xml
			eventslist.clear();

			new newDeviceConfiguration().execute();
		}
	}

	// DownloadJSON AsyncTask
	private class newDeviceConfiguration extends AsyncTask<Void, Void, Void> {

		private final String TAG = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
		}

		@Override
		protected Void doInBackground(Void... params) {
			// Create the array
			mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE,
					null);
			Cursor allrawdevice = null;
			try {
				String query = "SELECT * FROM table_device ORDER BY device_id DESC";
				allrawdevice = mydb.rawQuery(query, null);
			} catch (Exception e) {
			}
			if (allrawdevice != null) {
				if (allrawdevice.getCount() > 0) {
					while (allrawdevice.moveToNext()) {
						String updateID = allrawdevice.getString(0);
						IMEINumber = allrawdevice.getString(1);
						longitude = allrawdevice.getString(2);
						latitude = allrawdevice.getString(3);
						currentVolumeStr = allrawdevice.getString(4);
						BateryLevelStr = allrawdevice.getString(5);
						String device_update_time = allrawdevice.getString(6);

					}
				}
			}

			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(sendingDeviceInfo);
				JSONObject json = new JSONObject();
				json.put("record1", IMEINumber);
				json.put("record2", deviceOpID);
				json.put("record3", Network);
				json.put("record4", "0");
				json.put("record5", latitude);
				json.put("record6", longitude);
				json.put("record7", BateryLevel);
				json.put("record8", currentVolume);

				JSONArray postjson = new JSONArray();
				postjson.put(json);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {
						arraylist = new ArrayList<HashMap<String, String>>();
						jsonobject = new JSONObject(result);
						try {
							// Locate the array name
							jsonarray = jsonobject.getJSONArray("posts");

							for (int i = 0; i < jsonarray.length(); i++) {
								HashMap<String, String> map = new HashMap<String, String>();
								jsonobject = jsonarray.getJSONObject(i);

								// Save Register OP in to Database
								mydb = openOrCreateDatabase(DATABASE_NAME,
										Context.MODE_PRIVATE, null);
								String UserMail = jsonobject.getString("email");
								ContentValues newrowfDealer = new ContentValues();
								Cursor checkUser = null;
								try {
									String query = "SELECT * FROM table_user Where user_carer_email = '"
											+ UserMail + "'";
									checkUser = mydb.rawQuery(query, null);
								} catch (Exception e) {
								}

								if (checkUser != null) {
									if (checkUser.getCount() > 0) {
										while (checkUser.moveToNext()) {
											ContentValues updateUser = new ContentValues();
											String updateID = checkUser
													.getString(0);
											String phone = checkUser
													.getString(5);
											// Log.e("ERROR :", "Registered User Update:" + phone);
											
											updateUser.put("user_carer_id",
															jsonobject
																	.getString("carerID"));
											updateUser
													.put("user_carer_email",
															jsonobject
																	.getString("email"));
											updateUser.put("user_carer_name",
													jsonobject
															.getString("name"));
											updateUser
													.put("user_carer_sms",
															jsonobject
																	.getString("carerSMS"));
											updateUser.put("user_op_id",
													jsonobject
															.getString("opID"));
											updateUser
													.put("user_op_name",
															jsonobject
																	.getString("opName"));
											updateUser.put("user_reg_date",
													getAddDateTimeString()
															.toString());
											updateUser
													.put("user_secreat",
															jsonobject
																	.getString("password"));

											mydb.update(MEM_USER, updateUser,
													"user_id ='" + updateID
															+ "'", null);
											String phoneno = jsonobject.getString("carerSMS");
											// Log.e("ERROR :", "Registered User Update:" + phoneno);
										}
									} else {
										try {
											newrowfDealer
													.put("user_carer_id",
															jsonobject
																	.getString("carerID"));
											newrowfDealer
													.put("user_carer_email",
															jsonobject
																	.getString("email"));
											newrowfDealer.put(
													"user_carer_name",
													jsonobject
															.getString("name"));
											newrowfDealer
													.put("user_carer_sms",
															jsonobject
																	.getString("carerSMS"));
											newrowfDealer.put("user_op_id",
													jsonobject
															.getString("opID"));
											newrowfDealer
													.put("user_op_name",
															jsonobject
																	.getString("opName"));
											newrowfDealer.put("user_reg_date",
													getAddDateTimeString()
															.toString());
											newrowfDealer
													.put("user_secreat",
															jsonobject
																	.getString("password"));
											mydb.insert(MEM_USER, null,
													newrowfDealer);
										} catch (Exception e) {
											Log.e("ERROR :", "Register Fail");
										}
									}
								}
								mydb.close();
							}
						} catch (JSONException e) {
							Log.e("ERROR :", "Register Fail");
						}

					}
				}

			} catch (Exception e) {

			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			// Locate the listview in listview_main.xml
			checkingUnAcknoledge();
			// deleteAcknoledgeEvents();
			// flagUnAcknoledgeEvents();
		}

	}

	private String getAddDateTimeString() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	public long getNativeTimeStamp(String DateSend, String Time, String Tzone) {
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm zzzzz");
		Calendar c = Calendar.getInstance();
		Date d = null;

		try {
			d = ddMMMyyFormat
					.parse(DateSend.trim() + " " + Time.trim() + Tzone);

		} catch (ParseException e) {
			e.printStackTrace();
		}

		c.setTime(d);

		String date_to_string = ddMMMyyFormat
				.format(c.getTimeInMillis() / 1000);
		TimeStampValue = c.getTimeInMillis() / 1000;
		return c.getTimeInMillis() / 1000;
	}

	public void checkingUnAcknoledge() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);

		Cursor checkAcknoledgeevents = null;

		try {
			checkAcknoledgeevents = mydb.query(MEM_EVENT, null,
					"event_status='4' ", null, null, null, null);
		} catch (Exception e) {
		}
		if (checkAcknoledgeevents != null) {
			if (checkAcknoledgeevents.getCount() > 0) {
				while (checkAcknoledgeevents.moveToNext()) {
					String updateID = checkAcknoledgeevents.getString(1);
					String eventReminderNumber = checkAcknoledgeevents
							.getString(17);
					String event_ack_count = checkAcknoledgeevents
							.getString(15);
					String event_date = checkAcknoledgeevents.getString(6);
					String event_time = checkAcknoledgeevents.getString(7);
					String event_notify = checkAcknoledgeevents.getString(19);
					sumDateTime = event_date + " " + event_time;

					if (event_ack_count.equals(eventReminderNumber)) {
						ContentValues updateEvets = new ContentValues();
						
						if (event_notify.equals("txt")) {
							try {
								sendSMS(CareerPhone,
										"Your Memory Angel Care Taker  : "
												+ CareeerOPUser
												+ "  Didn't Acknowledge Event Scheduled at : "
												+ sumDateTime);
								updateEvets.put("event_status", "5");
								updateEvets.put("event_update_time",
										getAddDateTimeString().toString());
								mydb.update(MEM_EVENT, updateEvets, "event_log_id ='"
										+ updateID + "'", null);
							} catch (Exception e) {
								Log.e("SMS Exeption", e.getMessage(), e);
							}
						} else if(event_notify.equals("email")){
							new SendEmail().execute();
							updateEvets.put("event_status", "5");
							updateEvets.put("event_update_time",
									getAddDateTimeString().toString());
							mydb.update(MEM_EVENT, updateEvets, "event_log_id ='"
									+ updateID + "'", null);
						}

						// CareerEmail,CareerPhone
					}

				}
			}
		}
		checkAcknoledgeevents.close();
		mydb.close();
	}

	private class SendEmail extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... arg0) {

			// String possibleEmail = sendingEmail;

			String possibleEmail = CareerEmail;

			TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
			// String PhoneNo1 = PhoneNo;

			try {
				if (possibleEmail != "") {

					// Log.e("Possible Main ", possibleEmail);

					GMailSender sender = new GMailSender(
							"devteam@mirzabros.com", "445am445pm@#");

					sender.sendMail("Unacknowledged Notification for "
							+ CareeerOPUser, "Dear " + CareerName + ","
							+ "\n Your Memory Angel Care Taker :"
							+ CareeerOPUser
							+ "   Didn't Acknowledge Event Scheduled at : "
							+ sumDateTime + "."
							+ ". \n Kind Regards, \n Memory Angel Team",
							"devteam@mirzabros.com", possibleEmail);

				} else {
					Log.e("Error SendMail", "No Registered mail account");
				}
			} catch (Exception e) {
				Log.e("SendMail", e.getMessage(), e);
			}

			return null;
		}

	}

	private String getAddDateTimeStringStamp() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyyMMddHHmm");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	// Flag unacknoledge events
	public void flagUnAcknoledgeEvents() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		/*
		 * int gmtOffset = TimeZone.getDefault().getRawOffset(); long
		 * nowunixtime = (System.currentTimeMillis() + gmtOffset) / 1000;
		 */
		String nowunixtime = getAddDateTimeStringStamp().toString();

		Cursor checkPreUnAckEvents = null;
		try {
			String query = "SELECT event_log_id,event_alam_time FROM table_events Where event_active = '0' AND event_alam_time < '"
					+ nowunixtime + "'";
			checkPreUnAckEvents = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}
		if (checkPreUnAckEvents != null) {
			if (checkPreUnAckEvents.getCount() > 0) {
				while (checkPreUnAckEvents.moveToNext()) {
					ContentValues updateEvets = new ContentValues();
					String updateID = checkPreUnAckEvents.getString(0);
					updateEvets.put("event_status", "4");
					updateEvets.put("event_update_time", getAddDateTimeString()
							.toString());
					mydb.update(MEM_EVENT, updateEvets, "event_log_id ='"
							+ updateID + "'", null);

				}
			}
		}
		checkPreUnAckEvents.close();
		mydb.close();
		// sendSMS(PhoneNo1, "Memory Angel Subscription Has Expired");
	}


	public class GetLocationNetGPS implements LocationListener {

		Context mContext;

		Location l = null;

		private GetLocationNetGPS(Context mContext) {
			this.mContext = mContext;
		}

		private double[] GetLoc() {
			LocationManager lm = (LocationManager) mContext
					.getSystemService(Context.LOCATION_SERVICE);

			lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
					this);

			List<String> providers = lm.getProviders(true);

			/*
			 * Loop over the array backwards, and if you get an accurate
			 * location, then break out the loop
			 */

			for (int i = providers.size() - 1; i >= 0; i--) {
				/* l = lm.getLastKnownLocation(providers.get(i)); */
				l = lm.getLastKnownLocation(providers.get(i));

				// Log.d("isProviderEnabled :",""+lm.isProviderEnabled(providers.get(i)));

				if (l != null)
					break;
			}

			double[] gps = new double[2];
			if (l != null) {
				gps[0] = l.getLatitude();
				gps[1] = l.getLongitude();
			}
			return gps;
		}

		@Override
		public void onLocationChanged(Location newLoc) {
			// Toast.makeText(getBaseContext(),
			// "Location Updated",Toast.LENGTH_SHORT).show();
			l = newLoc;
			// Log.d("Location In Update: ",""+l.getLatitude());
		}

		@Override
		public void onProviderDisabled(String arg0) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onProviderEnabled(String arg0) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
			// TODO Auto-generated method stub

		}

	}

	void getCurrentVolume() {
		// TODO Auto-generated method stub
		AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		currentVolume = audio.getStreamVolume(AudioManager.STREAM_RING);
		Log.v(TAG, "vOLUME :" + currentVolume);
	}

	void getDeviceInfo() {
		// TODO Auto-generated method stub
		// Get EMI Number
		TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		IMEINumber = tm.getDeviceId();
		Log.v(TAG, "XXX 1 :" + IMEINumber);
		// Get the SIM state
		SIMState = tm.getSimState();
		switch (SIMState) {
		case TelephonyManager.SIM_STATE_ABSENT:
			Network = 5;
			break;
		case TelephonyManager.SIM_STATE_NETWORK_LOCKED:
			Network = 2;
			break;
		case TelephonyManager.SIM_STATE_PIN_REQUIRED:
			Network = 3;
			break;
		case TelephonyManager.SIM_STATE_PUK_REQUIRED:
			Network = 4;
			break;
		case TelephonyManager.SIM_STATE_READY:
			Network = 1;
			break;
		case TelephonyManager.SIM_STATE_UNKNOWN:
			Network = 6;
			break;
		}
	}

	private void sendSMS(String phoneNumber, String message) {
		String SENT = "SMS_SENT";
		String DELIVERED = "SMS_DELIVERED";

		PendingIntent sentPI = PendingIntent.getBroadcast(
				BackgroundService.this, 0, new Intent(SENT), 0);

		PendingIntent deliveredPI = PendingIntent.getBroadcast(
				BackgroundService.this, 0, new Intent(DELIVERED), 0);

		registerReceiver(new BroadcastReceiver() {
			@Override
			public void onReceive(Context arg0, Intent arg1) {
				switch (getResultCode()) {
				case Activity.RESULT_OK:
					/*
					 * Toast.makeText(getBaseContext(), "SMS sent",
					 * Toast.LENGTH_SHORT).show();
					 */
					// Log.e("SMS sent", "SMS sent");
					break;
				case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
					/*
					 * Toast.makeText(getBaseContext(), "Generic failure",
					 * Toast.LENGTH_SHORT).show();
					 */
					break;
				case SmsManager.RESULT_ERROR_NO_SERVICE:
					/*
					 * Toast.makeText(getBaseContext(), "No service",
					 * Toast.LENGTH_SHORT).show();
					 */
					break;
				case SmsManager.RESULT_ERROR_NULL_PDU:
					/*
					 * Toast.makeText(getBaseContext(), "Null PDU",
					 * Toast.LENGTH_SHORT).show();
					 */
					break;
				case SmsManager.RESULT_ERROR_RADIO_OFF:
					/*
					 * Toast.makeText(getBaseContext(), "Radio off",
					 * Toast.LENGTH_SHORT).show();
					 */
					break;
				}
			}
		}, new IntentFilter(SENT));

		registerReceiver(new BroadcastReceiver() {
			@Override
			public void onReceive(Context arg0, Intent arg1) {
				switch (getResultCode()) {
				case Activity.RESULT_OK:
					/*
					 * Toast.makeText(getBaseContext(), "SMS delivered",
					 * Toast.LENGTH_SHORT).show();
					 */
					break;
				case Activity.RESULT_CANCELED:
					/*
					 * Toast.makeText(getBaseContext(), "SMS not delivered",
					 * Toast.LENGTH_SHORT).show();
					 */
					break;
				}
			}
		}, new IntentFilter(DELIVERED));

		SmsManager sms = SmsManager.getDefault();
		sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
	}

	private String getAddDateTimeStringPreCheck() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyyMMddHHmm");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

}
